import pygame
import copy
from settings_manager import *
from state_manager import *

from highscore_scene import HighscoreScene
from pygame.sprite import LayeredDirty

from button import *
from events import *

path = "data/textures/"

class SubmitScore:
	refresh = False
	pWin = 0
	points = 0

	def __init__(self, screen):
		self.screen = screen

	def create(self):
		self.group = LayeredDirty()

		self.background = pygame.image.load(path + str(SettingsManager.settings.resolution[0]) + "_submit_background.jpg")
		self.baseBackground = copy.copy(self.background)

		self.bSubmit = Button(path + "submit1.png", path + "submit2.png", path + "submit3.png")
		
		#Set buttons in place
		self.width, self.height = self.screen.get_rect().width, self.screen.get_rect().height
		bWidth, bHeight = self.bSubmit.rect.width, self.bSubmit.rect.height

		posX = self.width / 2 - bWidth / 2
		posY = self.height / 2 + bHeight
		self.bSubmit.rect.x = posX
		self.bSubmit.rect.y = posY

		self.group.add(self.bSubmit)

		#Font
		self.size = 36
		self.font = pygame.font.Font(None, self.size)
		self.name = ""

	def update(self):
		if StateManager.state.window != StateConst.SubmitScore:
			return None #Escape submitscore updating

		if SubmitScore.refresh:
			SubmitScore.refresh = False
			self.create()

		self.background = copy.copy(self.baseBackground)
		self.text = self.font.render("Player " + str(SubmitScore.pWin) + " won  " + "Points : " + str(SubmitScore.points) + "    Name : " + self.name, 1, (10, 10, 10))
		self.background.blit(self.text, (30, self.height / 2))
		
		for event in Events.events:
			if event.type == pygame.KEYUP:
				if event.key == pygame.K_BACKSPACE:
					self.name = self.name[:len(self.name) - 1]
				elif event.key < 256:
					self.name = self.name + chr(event.key)

		self.manageButtonsClicks()

		self.drawSubmitScore()


	def manageButtonsClicks(self):
		if self.bSubmit.isClicked():
			StateManager.changeWindow(StateConst.MainMenu)
			StateManager.changeSound(StateConst.MainMenuSound)

			#write the name
			with open("data/score/" + "scores", "a") as f:
				f.write(str(SubmitScore.points) + " " + self.name + "\n")

			HighscoreScene.refresh = True

	
	def drawSubmitScore(self):
		self.group.clear(self.screen, self.background)
		update_area = self.group.draw(self.screen)
		pygame.display.update(update_area)
		self.group.update()
